import QRCode from 'qrcode'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import { useAgentStore } from '@/store/modules/agent'
// 渠道码相关工具
// 生成渠道码
async function generateChannelCode(text) {
  return QRCode.toDataURL(
    text,
    {
      errorCorrectionLevel: 'H',
      margin: 1,
      width: 200,
      height: 200
    },
  )
}
// 导出渠道码
async function exportChannelCode(channelList, channelType) {
  const zip = new JSZip()
  const promises = [] as any
  channelList.forEach((dataItem) => {
    const promise = new Promise(async (resolve, reject) => {
      try {
        const url = await generateChannelCode(`${useAgentStore().channelBaseUrl}?channelId=${dataItem.activityChannelId}&channelType=${dataItem.channelType}`)
        const img = new Image()
        img.src = url
        img.onload = () => {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d') as any
          // 扩大画布高度以容纳两行文字
          canvas.width = img.width
          canvas.height = img.height + 90  // 从 +30 改为 +60

          ctx.drawImage(img, 0, 0)

          // 绘制更大的白色背景矩形
          ctx.fillStyle = 'white'
          ctx.fillRect(0, img.height, canvas.width, 90)  // 高度从 30 改为 60

          // 第一行文字（网点号-渠道码）
          ctx.font = 'bold 14px Arial'
          const line1 =  dataItem.channelCode
          const textWidth1 = ctx.measureText(line1).width
          const x1 = (canvas.width - textWidth1) / 2
          const y1 = img.height + 20  // 第一行垂直位置
          ctx.fillStyle = 'black'
          ctx.fillText(line1, x1, y1)

          // 新增的第二行文字（公众号appId）
          const line2 = `${dataItem.appName}`
          const textWidth2 = ctx.measureText(line2).width
          const x2 = (canvas.width - textWidth2) / 2
          const y2 = img.height + 45  // 第二行垂直位置（比第一行低25像素）
          ctx.fillText(line2, x2, y2)

          // 新增的第三行文字（域名）
          const line3 = `【${useAgentStore().hostname}】`
          const textWidth3 = ctx.measureText(line3).width
          const x3 = (canvas.width - textWidth3) / 2
          const y3 = img.height + 70  // 第二行垂直位置（比第一行低25像素）
          ctx.fillText(line3, x3, y3)
          const dataUrl = canvas.toDataURL('image/png')

          var imgZ = zip.folder('活动渠道码') as any
          if (dataItem.agentNameList) {
            dataItem?.agentNameList.forEach((item) => {
              imgZ = imgZ.folder(item)
            })
          } else if (channelType === 0) {
            imgZ = imgZ.folder('机构员工渠道')
          } else if (channelType === 2) {
            imgZ = imgZ.folder('机构网点渠道')
          } else if (channelType === 1) {
            imgZ = imgZ.folder('商户渠道')
          }  else if (channelType === 3) {
            imgZ = imgZ.folder('商户渠道')
          } 
          else {
            imgZ = imgZ.folder('其他')
          }

          imgZ = imgZ.folder(dataItem.channelName)
          imgZ.file(
            // (dataItem.agentNo4 || dataItem.channelCode) + '-' + 
            dataItem.channelCode + '-' + dataItem.appId + '.png',
            dataUrl.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''),
            { base64: true }
          )
          resolve(null)
        }
      } catch (error) {
        resolve(null)
      }
    })
    promises.push(promise)
  })
  await Promise.all(promises)
  zip.generateAsync({ type: 'blob' }).then((content) => {
    saveAs(content, '活动渠道码.zip')
  })
}
// 暴露接口
export {
  generateChannelCode,
  exportChannelCode
}